﻿namespace TomatoBreak.Web
{
    using System;
    using System.Web.Mvc;
    using Infrastructure;

    public class CurrentUser : IMvcFilter, IActionFilter
    {
        private readonly ICurrentUserProvider userProvider;

        public CurrentUser(ICurrentUserProvider userProvider)
        {
            if (userProvider == null)
            {
                throw new ArgumentNullException("userProvider");
            }

            this.userProvider = userProvider;

            Order = 2;
        }

        public int Order { get; set; }

        public bool AllowMultiple
        {
            get { return false; }
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            SetUser(filterContext.Controller);
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            SetUser(filterContext.Controller.ViewData.Model);
        }

        protected virtual void SetUser(object service)
        {
            var userAware = service as ICurrentUserAware;

            if (userAware == null)
            {
                return;
            }

            var user = userProvider.CurrentUser;

            if (user != null)
            {
                userAware.SetCurrentUser(user);
            }
        }
    }
}